package com.rtf.framework.web.mvc.config.session;

import com.rtf.framework.common.config.AppProperties;
import com.rtf.framework.common.config.AppSecureProperties;
import com.rtf.framework.common.dto.UtilDTO;
import com.rtf.framework.common.exception.AppException;
import com.rtf.framework.common.secure.auth.AppUserDetailsDefault;
import com.rtf.framework.common.util.UtilCollection;
import com.rtf.framework.common.util.UtilString;
import com.rtf.framework.web.mvc.config.session.common.AppUserInfo;
import com.rtf.framework.web.mvc.config.session.common.AppUtilHttpClient;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mzlion.core.json.TypeRef;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 *session登录用户信息获取类
 *
 * @author liuke
 * @date  2021/8/2 16:45
 * @version
*/
@Slf4j
public class AppQueryUserDetail {

    /**
     *获取用户信息
     * 
     * @param idcardHash
     * @param appProperties
     * @param appSecureProperties 
     * @author liuke
     * @date 2021/8/2 16:52
     * @return com.rtf.framework.common.secure.auth.AppUserDetailsDefault
     */
    public static AppUserDetailsDefault getUserDetails(String idcardHash, AppProperties appProperties, AppSecureProperties appSecureProperties,List<AppUserDetailConvertService> appUserDetailConvertServices){

        Map<String,Object> searchParam = Maps.newHashMap();
        if(UtilString.isBlank(appSecureProperties.getSso().getOauth2Configs().get(0).getClientId())){
            throw new AppException("配置中心SSO配置未定义ClientId");
        }
        searchParam.put("idcardHash",idcardHash);
        searchParam.put("clientId",appSecureProperties.getSso().getOauth2Configs().get(0).getClientId());

        //判断是否有sso地址
        if(UtilString.isBlank(appProperties.getSsoQueryUserInfoPath())){
            throw new AppException("未定义SSO用户信息获取路径");
        }
        //获取用户信息
        AppUserInfo userInfo = AppUtilHttpClient.sendJson(appProperties.getSsoQueryUserInfoPath(),searchParam).asBean(new TypeRef<AppUserInfo>() {});
        if(userInfo==null|| UtilString.isBlank(userInfo.getUsername())){
            return null;
        }else {
            AppUserDetailsDefault appUserDetailsDefault = convert(userInfo);
            //转换用户信息
            for (AppUserDetailConvertService appUserDetailConvertService : appUserDetailConvertServices) {
                appUserDetailConvertService.convertUserDetailsDefault(appUserDetailsDefault);
            }
            return appUserDetailsDefault;

        }
    }


    /**
     *
     * 将用户信息转换为AppUserDetailsDefault
     * @param ssoUserInfo 
     * @author liuke
     * @date 2021/8/2 16:53
     * @return com.rtf.framework.common.secure.auth.AppUserDetailsDefault
     */
    private static AppUserDetailsDefault convert(AppUserInfo ssoUserInfo){
        AppUserDetailsDefault appUserDetailsDefault = new AppUserDetailsDefault(ssoUserInfo.getUsername());
        // 设置登录用户来源为oauth2
        appUserDetailsDefault.setAuthSource("oauth2");
        // 设置用户id
        appUserDetailsDefault.setUserId(ssoUserInfo.getUserId());
        // 设置用户真实姓名
        appUserDetailsDefault.setUserRealName(ssoUserInfo.getName());
        // 设置用户手机号
        appUserDetailsDefault.setTelephone(ssoUserInfo.getTelephone());

        // 装载用户授权
        appUserDetailsDefault.getAuthorities().addAll(convertRoleToGrantedAuthority(ssoUserInfo.getAuthorities()));
        // 设置用户其它属性

        Map<String,Object> userProperties = ssoUserInfo.getUserProperties();
        userProperties.put("logo",ssoUserInfo.getLogo());
        userProperties.put("hash",ssoUserInfo.getHash());
        userProperties.put("username",ssoUserInfo.getUsername());
        userProperties.put("idCardHash",ssoUserInfo.getIdCardHash());
        userProperties.put("roles", UtilDTO.toDTO(ssoUserInfo.getRoles(),null,null,null));
        appUserDetailsDefault.setUserProperties(userProperties);
        return appUserDetailsDefault;
    }

    /**
     *
     * 转换authorities
     * @param authorities 
     * @author liuke
     * @date 2021/8/3 19:31
     * @return java.util.Collection<org.springframework.security.core.GrantedAuthority>
     */
    public static Collection<GrantedAuthority> convertRoleToGrantedAuthority(List<Map<String, Object>> authorities ) {
        Set<GrantedAuthority> grantedAuthorities = Sets.newHashSet() ;
        if(UtilCollection.isEmpty(authorities)){
            return grantedAuthorities;
        }

        authorities.stream().forEach(stringObjectMap -> {
            grantedAuthorities.add(new SimpleGrantedAuthority(stringObjectMap.get("authority").toString()));
        });

        return grantedAuthorities ;
    }

}
